package graphiceditor4robot.more.actions;

import graphiceditor4robot.more.wizard.FsmCreationFromBehaviourWizard;

import org.eclipse.emf.ecore.EObject;
import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.FileEditorInput;

import behaviourdiagram.Behaviour;

public class CreateFSM implements IWorkbenchWindowActionDelegate {

	private Behaviour behaviour;

	private IStructuredSelection selection;

	public CreateFSM() {
	}

	@Override
	public void run(IAction action) {
		if (behaviour == null)
			return;
		IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
		
		if (page == null)
			return;
	
		IEditorInput input = page.getActiveEditor().getEditorInput();
		if (input instanceof FileEditorInput)
		{
			Shell shell = page.getWorkbenchWindow().getShell();
			FsmCreationFromBehaviourWizard wizard = new FsmCreationFromBehaviourWizard();
			wizard.init(PlatformUI.getWorkbench(), behaviour.getName(), selection);
			WizardDialog dialog = new WizardDialog(shell, wizard);
	        dialog.create();
	        dialog.open();
		}
	}

	@Override
	public void selectionChanged(IAction action, ISelection selection) {
		if (selection == null){
			return;
		}
		if (selection instanceof IStructuredSelection) {
			IStructuredSelection sel = (IStructuredSelection)selection;
			Object obj = sel.getFirstElement();
			if (obj instanceof IGraphicalEditPart) {
				EObject o = ((IGraphicalEditPart)obj).getNotationView().getElement();
				if (o instanceof Behaviour) {
					behaviour = (Behaviour)o;
					this.selection = (IStructuredSelection) selection;
				}
			}
		}
	}

	@Override
	public void dispose() {
	}

	@Override
	public void init(IWorkbenchWindow window) {
		
	}


}
